/* ----------------------------------------------------------------------------
 * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved.
 * Description: Queue Debug
 * Author: huangjieliang
 * Create: 2013-01-01
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior written
 * permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * --------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------------
 * Notice of Export Control Law
 * ===============================================
 * Huawei LiteOS may be subject to applicable export control laws and regulations, which might
 * include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
 * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
 * applicable export control laws and regulations.
 * --------------------------------------------------------------------------- */

#include "los_typedef.h"
#include "los_hw_pri.h"
#include "los_queue_pri.h"
#ifdef LOSCFG_SHELL
#include "shcmd.h"
#endif /* LOSCFG_SHELL */

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* __cplusplus */

#ifdef LOSCFG_DEBUG_QUEUE
typedef struct{
    VOID    *creater;       /**< The task entry who created this queue  */
    UINT64  lastAccessTime; /**< The last access time                   */
} QueueDebugCB;

STATIC QueueDebugCB *g_queueDebugArray;

/* This sort function is modified from MUX. */
STATIC VOID osArraySortByTime(UINT32 *sortArray, UINT32 start, UINT32 end)
{
    UINT32 left = start;
    UINT32 right = end;
    UINT32 idx = start;
    UINT32 pivot = sortArray[start];

    while (left < right) {
        while (left < right &&
               g_queueDebugArray[sortArray[right]].lastAccessTime > g_queueDebugArray[pivot].lastAccessTime) {
            right--;
        }

        if (left < right) {
            sortArray[left] = sortArray[right];
            idx = right;
            left++;
        }

        while (left < right &&
               g_queueDebugArray[sortArray[right]].lastAccessTime < g_queueDebugArray[pivot].lastAccessTime) {
            left++;
        }

        if (left < right) {
            sortArray[right] = sortArray[left];
            idx = left;
            right--;
        }
    }

    sortArray[idx] = pivot;

    if (start < idx) {
        osArraySortByTime(sortArray, start, idx - 1);
    }
    if (idx < end) {
        osArraySortByTime(sortArray, idx + 1, end);
    }
}

VOID osQueueDbgInit(VOID)
{
    g_queueDebugArray = (QueueDebugCB *)LOS_MemAlloc(m_aucSysMem0, LOSCFG_BASE_IPC_QUEUE_LIMIT * sizeof(QueueDebugCB));
    if (g_queueDebugArray == NULL) {
        PRINT_ERR("%s: malloc failed!\n", __FUNCTION__);
        return;
    }
}

VOID osQueueDbgTimeUpdate(UINT32 queueID)
{
    QueueDebugCB *queueDebug = &g_queueDebugArray[GET_QUEUEINDEX(queueID)];
    queueDebug->lastAccessTime = LOS_TickCountGet();
    return;
}

VOID osQueueDbgUpdate(UINT32 queueID, VOID *entry)
{
    QueueDebugCB *queueDebug = &g_queueDebugArray[GET_QUEUEINDEX(queueID)];
    queueDebug->creater = entry;
    queueDebug->lastAccessTime = LOS_TickCountGet();
    return;
}

VOID osQueueCheck(VOID)
{
    LosQueueCB *queueNode = NULL;
    UINT32 index;
    UINT32 count = 0;
    UINT32 sysCount = 0;
    UINT32 *indexArray = (UINT32 *)LOS_MemAlloc((void *)OS_SYS_MEM_ADDR, LOSCFG_BASE_IPC_QUEUE_LIMIT * sizeof(UINT32));
    QueueDebugCB *queueDebugNode = (QueueDebugCB *)NULL;
    for (index = 0; index < LOSCFG_BASE_IPC_QUEUE_LIMIT; index++) {
        queueNode = GET_QUEUE_HANDLE(index);
        queueDebugNode = &g_queueDebugArray[index];
        if (queueNode->queueState == OS_QUEUE_UNUSED ||
            (queueNode->queueState == OS_QUEUE_INUSED && queueDebugNode->creater == NULL)) {
            continue;
        }
        if (queueNode->queueState == OS_QUEUE_INUSED &&
            queueNode->queueLen == queueNode->readWriteableCnt[OS_QUEUE_WRITE] &&
            LOS_ListEmpty(&queueNode->readWriteList[OS_QUEUE_READ]) &&
            LOS_ListEmpty(&queueNode->readWriteList[OS_QUEUE_WRITE]) &&
            LOS_ListEmpty(&queueNode->memList)) {
            PRINTK("Queue ID <0x%x> may leak, No task uses it, "
                   "QueueLen is 0x%x, TaskEntry of creater: %p, Latest operation time: 0x%llx\n",
                   queueNode->queueID,
                   queueNode->queueLen,
                   g_queueDebugArray[index].creater,
                   g_queueDebugArray[index].lastAccessTime);
        } else {
            if (indexArray != NULL) {
                *(indexArray + count) = index;
                count++;
            } else {
                PRINTK("Queue ID <0x%x> may leak, queue len is 0x%x, "
                       "readable cnt:0x%x, writeable cnt:0x%x, "
                       "TaskEntry of creater:0x%p, Latest operation time: 0x%llx\n",
                       queueNode->queueID,
                       queueNode->queueLen,
                       queueNode->readWriteableCnt[OS_QUEUE_READ],
                       queueNode->readWriteableCnt[OS_QUEUE_WRITE],
                       g_queueDebugArray[index].creater,
                       g_queueDebugArray[index].lastAccessTime);
            }
        }
    }

    if (indexArray != NULL) {
        if (count > 0) {
            osArraySortByTime(indexArray, 0, count - 1);
            for (index = 0; index < count; index++) {
                queueNode = GET_QUEUE_HANDLE(indexArray[index]);
                queueDebugNode = &g_queueDebugArray[indexArray[index]];
                PRINTK("Queue ID <0x%x> may leak, queue len is 0x%x, "
                       "readable cnt:0x%x, writeable cnt:0x%x, "
                       "TaskEntry of creater:%p, Latest operation time: 0x%llx\n",
                       queueNode->queueID,
                       queueNode->queueLen,
                       queueNode->readWriteableCnt[OS_QUEUE_READ],
                       queueNode->readWriteableCnt[OS_QUEUE_WRITE],
                       queueDebugNode->creater,
                       queueDebugNode->lastAccessTime);
            }
        }
        (VOID)LOS_MemFree((void *)OS_SYS_MEM_ADDR, indexArray);
    }
    return;
}

#ifdef LOSCFG_SHELL
LITE_OS_SEC_TEXT_MINOR UINT32 osShellCmdQueueInfoGet(UINT32 argc, CHAR **argv)
{
    if (argc > 0) {
        PRINTK("\nUsage: queue\n");
        return OS_ERROR;
    }
    PRINTK("used queues information: \n");
    osQueueCheck();
    return LOS_OK;
}

SHELLCMD_ENTRY(queue_shellcmd, CMD_TYPE_EX, "queue", 0, (CMD_CBK_FUNC)osShellCmdQueueInfoGet); /*lint !e19*/
#endif /* LOSCFG_SHELL */
#endif /* LOSCFG_DEBUG_QUEUE */

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
